package com.elitel.frame.business.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.elitel.common.exception.BusinessStatementException;
import com.elitel.common.utils.XCommonUtils;
import com.elitel.frame.base.component.RedisCacheComponent;
import com.elitel.frame.base.component.RedisCacheDataBase;
import com.elitel.frame.business.service.SingleEditService;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.CfgEdit;
import com.elitel.frame.main.entity.enums.ResponseStatusCodeEnum;
import com.elitel.frame.main.entity.ext.BaseEditconfigExt;
import com.elitel.frame.main.entity.vo.JsonDataResult;
import com.elitel.frame.main.entity.vo.ValidationInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Description 单表编辑服务接口
 *
 * @author guoyanfei date 2018/01/08
 */
@Controller
@RequestMapping("/business/singleEditServer")
@Api(value = "/business/singleEditServer", tags = "单表编辑服务接口")
public class SingleEditServerController {
  private static final Logger logger = LoggerFactory.getLogger(SingleEditServerController.class);

  @Autowired private RedisCacheComponent redisCacheComponent;
  @Autowired private SingleEditService singleEditService;
  @Autowired private RedisCacheDataBase redisCacheDataBase;

  /** 文件上传临时路径 */
  @Value("${elitel.file.path}")
  private String filepath;

  /**
   * Description 单表新增服务接口
   *
   * @param serviceID (服务ID)
   * @param conQuery (新增的值，格式:{key:value,key:value,key:value....})
   * @return JsonDataResult实体
   * @author guoyanfei date 2018/01/08
   */
  @RequestMapping(value = "/singleAdd")
  @ResponseBody
  @ApiOperation(value = "单表新增服务接口")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(
        name = "conQuery",
        value = "新增的值，格式:{key:value,key:value,key:value....}",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public Object singleAdd(String serviceID, String conQuery) {

      JsonDataResult jsonDataResult = checkParameter(serviceID, conQuery);
      if(jsonDataResult != null)
        return jsonDataResult;

      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if(cfgEdit == null){
        return JsonDataResult.builder()
          .result(ResponseStatusCodeEnum.SERVICE_MISSION.statusCode())
          .message("服务不存在").build();
      }

      CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
      try {
          ValidationInfoVo validationInfoVo = singleEditService.addInfo(cfgEdit, cfgDb, conQuery);

          if (!validationInfoVo.getIspass()) {
            return JsonDataResult.builder().result(ResponseStatusCodeEnum.VALIDATE_ERROR.statusCode()).message(validationInfoVo.getValidateMessage()).build();
          }
          return JsonDataResult.responseSuccess(validationInfoVo.getCount());

      } catch (BusinessStatementException e) {
            return JsonDataResult.responseError("exceptionMessage: " + e.getExceptionMessage() + "\r\n customMessage: " + e.getCustomMessage());

      } catch (Exception e) {
        logger.error("单表新增服务异常", e);
        return JsonDataResult.builder().result(ResponseStatusCodeEnum.ERROR.statusCode()).message("单表新增异常:" + e.getMessage()).build();
      }
  }

  private JsonDataResult checkParameter(String serviceID, String conQuery){

      if (XCommonUtils.isEmpty(serviceID)) {
        return JsonDataResult.builder()
          .result(ResponseStatusCodeEnum.PARAMETER_ERROR.statusCode())
          .message("serviceID没有传入值或拼写错误!").build();
      }
      if (XCommonUtils.isEmpty(conQuery)) {
        return JsonDataResult.builder()
          .result(ResponseStatusCodeEnum.PARAMETER_ERROR.statusCode())
          .message("conQuery没有传入值或拼写错误!").build();
      }

      return null;

  }


  /**
   * Description 单边编辑修改服务
   *
   * @param serviceID (服务ID)
   * @param conQuery (修改的值，格式:{key:value,key:value,key:value....})
   * @return JsonDataResult实体
   * @author guoyanfei date 2018/01/08
   */
  @RequestMapping(value = "/singleUpdate")
  @ResponseBody
  @ApiOperation(value = "单边编辑修改服务接口")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(
        name = "conQuery",
        value = "修改的值，格式:{key:value,key:value,key:value....}",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public Object singleUpdate(String serviceID, String conQuery) {
      JsonDataResult jsonResult = checkParameter(serviceID, conQuery);
      if(jsonResult != null)
        return jsonResult;

      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if(cfgEdit == null){
        return JsonDataResult.builder().result(ResponseStatusCodeEnum.SERVICE_MISSION.statusCode()).message("服务不存在").build();
      }

      CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
      ValidationInfoVo validationInfoVo = null;

      try {
          //  判断 conQuery 类型
          if (conQuery.startsWith("[")) {
            JSONArray updateData = JSON.parseArray(conQuery);
            for (int i = 0; i < updateData.size(); i++) {
              Object object = updateData.get(i);
              String conQ = JSON.toJSONString(object);
              validationInfoVo = singleEditService.updateInfo(cfgEdit, cfgDb, conQ);
            }
          } else {
            validationInfoVo = singleEditService.updateInfo(cfgEdit, cfgDb, conQuery);
          }

          if (!validationInfoVo.getIspass()) {
            return JsonDataResult.builder().result(ResponseStatusCodeEnum.VALIDATE_ERROR.statusCode()).message(validationInfoVo.getValidateMessage()).build();
          }
          return JsonDataResult.responseSuccess(validationInfoVo.getCount());

      } catch (BusinessStatementException e) {
          return JsonDataResult.responseError("exceptionMessage: " + e.getExceptionMessage() + "\r\n customMessage: " + e.getCustomMessage());

      } catch (Exception e) {
          logger.error("单表修改异常", e);
          return JsonDataResult.builder().result(ResponseStatusCodeEnum.ERROR.statusCode()).message("单表新增异常:" + e.getMessage()).build();
      }
  }

  /**
   * Description 单表编辑删除服务
   *
   * @param serviceID 服务ID
   * @param primaryKeys 主键值，多个值以','分割
   * @return JsonDataResult
   * @author guoyanfei date 2018/01/08
   */
  @RequestMapping(value = "/singleDel")
  @ResponseBody
  @ApiOperation(value = "单表编辑删除服务")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(
        name = "primaryKeys",
        value = "主键值，多个值以','分割,多个主键已'_'分割",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public Object singleDel(String serviceID, String primaryKeys) {
    JsonDataResult jsonResult = new JsonDataResult();
    try {
      if (serviceID == null || serviceID.equals("")) {
        jsonResult.setResult(901);
        jsonResult.setMessage("serviceID没有传入值或拼写错误!");
        return jsonResult;
      }
      if (primaryKeys == null || primaryKeys.equals("")) {
        jsonResult.setResult(901);
        jsonResult.setMessage("primaryKeys没有传入值或拼写错误!");
        return jsonResult;
      }
      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if (cfgEdit != null) {
        CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
        ValidationInfoVo validationInfoVo = new ValidationInfoVo();
        validationInfoVo = singleEditService.delInfo(cfgEdit, cfgDb, primaryKeys);
        if (validationInfoVo.getIspass()) {
          jsonResult.setResult(0);
          jsonResult.setData(validationInfoVo.getCount());
          jsonResult.setMessage("删除成功!");
        } else {
          jsonResult.setResult(801);
          jsonResult.setMessage(validationInfoVo.getValidateMessage());
          jsonResult.setData(0);
        }
      } else {
        jsonResult.setResult(701);
        jsonResult.setMessage("服务不存在");
        jsonResult.setData(0);
      }

    } catch (Exception e) {
      logger.error("单表删除异常:", e);
      jsonResult.setResult(1);
      jsonResult.setMessage("单表删除异常:" + e.getMessage());
    }
    return jsonResult;
  }

  /**
   * Description 查询校验列
   *
   * @param serviceID (服务ID)
   * @return JsonDataResult实体
   * @author guoyanfei date 2018/01/11
   */
  @RequestMapping(value = "/selectValidateCoulmn", method = RequestMethod.GET)
  @ResponseBody
  @ApiOperation(value = "查询校验列")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public Object selectValidateCoulmn(String serviceID) {
    JsonDataResult jsonResult = new JsonDataResult();
    try {
      if (serviceID == null || serviceID.equals("")) {
        jsonResult.setResult(901);
        jsonResult.setMessage("serviceID没有传入值或拼写错误!");
        return jsonResult;
      }
      List<BaseEditconfigExt> baseEditconfigExts =
          redisCacheDataBase.selectBaseEditconfigRedisCache(serviceID);
      if (baseEditconfigExts != null && baseEditconfigExts.size() > 0) {
        jsonResult.setResult(0);
        jsonResult.setMessage("查询成功!");
        jsonResult.setData(baseEditconfigExts);
      } else {
        jsonResult.setResult(701);
        jsonResult.setMessage("没有配置校验列!");
        jsonResult.setData(0);
      }
    } catch (Exception e) {
      logger.error("单表编辑服务查询校验列异常:", e);
      jsonResult.setResult(1);
      jsonResult.setMessage("单表编辑服务查询校验列异常:" + e.getMessage());
    }
    return jsonResult;
  }

  /**
   * Description 通过服务ID下载数据模板
   *
   * @param serviceID (服务ID)
   * @author guoyanfei date 2018/01/17
   */
  @RequestMapping(value = "/downloadDataTemplate", method = RequestMethod.GET)
  @ResponseBody
  @ApiOperation(value = "通过服务ID下载数据模板")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public void downloadDataTemplate(HttpServletRequest request, HttpServletResponse response) {
    try {
      String serviceID = request.getParameter("serviceID");
      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if (cfgEdit != null) {
        // 查询表头
        List<ExcelExportEntity> beanList = new ArrayList<ExcelExportEntity>();
        List<BaseEditconfigExt> baseEditconfigExts =
            redisCacheDataBase.selectBaseEditconfigRedisCache(serviceID);
        if (baseEditconfigExts != null && baseEditconfigExts.size() > 0) {
          for (BaseEditconfigExt baseEditconfigExt : baseEditconfigExts) {
            beanList.add(
                new ExcelExportEntity(
                    baseEditconfigExt.getDfnameCn(), baseEditconfigExt.getDfname()));
          }
        }
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        Workbook workbook =
            ExcelExportUtil.exportExcel(
                new ExportParams(cfgEdit.getServicename() + "数据模板", cfgEdit.getServicename()),
                beanList,
                maps);
        String filename = serviceID;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        filename += formatter.format(currentTime) + ".xls";

        // 应用程序强制下载
        response.setContentType("application/force-download");
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        // 设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        OutputStream outStream = response.getOutputStream();
        workbook.write(outStream);
        outStream.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * Description 通过服务ID导出数据
   *
   * @param serviceID (服务ID)
   * @author guoyanfei date 2018/01/19
   */
  @RequestMapping(value = "/exportData", method = RequestMethod.GET)
  @ResponseBody
  @ApiOperation(value = "通过服务ID导出数据")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public void exportData(HttpServletRequest request, HttpServletResponse response) {
    try {
      String serviceID = request.getParameter("serviceID");
      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if (cfgEdit != null) {
        // 查询数据源
        CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());

        // 查询表头
        List<ExcelExportEntity> beanList = new ArrayList<ExcelExportEntity>();
        List<BaseEditconfigExt> baseEditconfigExts =
            redisCacheDataBase.selectBaseEditconfigRedisCache(serviceID);
        if (baseEditconfigExts != null && baseEditconfigExts.size() > 0) {
          for (BaseEditconfigExt baseEditconfigExt : baseEditconfigExts) {
            beanList.add(
                new ExcelExportEntity(
                    baseEditconfigExt.getDfnameCn(), baseEditconfigExt.getDfname()));
          }
        }
        List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
        maps = singleEditService.getAllData(cfgEdit, cfgDb);

        // 设置单元格样式
        ExportParams exportParams =
            new ExportParams(cfgEdit.getServicename() + "数据", cfgEdit.getServicename());
        exportParams.setColor(IndexedColors.BLACK.getIndex());
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, beanList, maps);

        String filename = serviceID;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        filename += formatter.format(currentTime) + ".xls";
        // 应用程序强制下载
        response.setContentType("application/force-download");
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        // 设置响应头，控制浏览器下载该文件
        response.setHeader("content-disposition", "attachment;filename=" + filename);
        OutputStream outStream = response.getOutputStream();
        workbook.write(outStream);
        outStream.close();
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @PostMapping(value = "/batchAddData/{serviceID}")
  @ResponseBody
  @ApiOperation(value = "批量添加数据")
  public Object batchAddData(
      @PathVariable String serviceID, @RequestBody List<Map<String, Object>> dataList) {
    JsonDataResult jsonDataResult = new JsonDataResult();
    jsonDataResult.setMessage("");

    // 服务信息
    CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
    if (cfgEdit == null) {
      jsonDataResult.setResult(902);
      jsonDataResult.setMessage("服务不存在!");
      return jsonDataResult;
    }

    // 数据源信息
    CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
    if (cfgDb == null) {
      jsonDataResult.setResult(903);
      jsonDataResult.setMessage("数据源不存在!");
      return jsonDataResult;
    }

    try {
      // 导入到数据库
      ValidationInfoVo validationInfoVo = singleEditService.batchImportData(dataList, cfgEdit, cfgDb);
      jsonDataResult.setData(1);
      jsonDataResult.setResult(0);
      jsonDataResult.setMessage(
          jsonDataResult.getMessage() + validationInfoVo.getValidateMessage());

    } catch (Exception e) {
      jsonDataResult.setResult(1);
      jsonDataResult.setData(0);
      jsonDataResult.setMessage(e.getMessage());
    }

    return jsonDataResult;
  }
  /**
   * Description 导入数据
   *
   * @return 导入结果
   * @author guoyanfei date 2018/01/19
   */
  @RequestMapping(value = "/importData", method = RequestMethod.POST)
  @ResponseBody
  @ApiOperation(value = "通过服务ID导入数据")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(
        name = "file",
        value = "导入Excel数据文件",
        required = true,
        dataType = "file",
        paramType = "form")
  })
  public Object importData(HttpServletRequest request) throws IllegalStateException, IOException {
    JsonDataResult jsonDataResult = new JsonDataResult();
    jsonDataResult.setMessage("");
    // 获取服务ID
    String serviceID = request.getParameter("serviceID");
    if (serviceID == null || serviceID.equals("")) {
      jsonDataResult.setResult(901);
      jsonDataResult.setMessage("serviceID没有传入值或拼写错误!");
      return jsonDataResult;
    }

    Integer flag = 0;
    try {
      if (request.getParameter("flag") != null
          && !request.getParameter("flag").equalsIgnoreCase("")) {
        flag = Integer.parseInt(request.getParameter("flag"));
      }
    } catch (Exception e) {
      jsonDataResult.setResult(904);
      jsonDataResult.setMessage("flag参数输入错误,默认值为0");
      return jsonDataResult;
    }

    // 服务信息
    CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
    if (cfgEdit == null) {
      jsonDataResult.setResult(902);
      jsonDataResult.setMessage("服务不存在!");
      return jsonDataResult;
    }

    // 数据源信息
    CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
    if (cfgDb == null) {
      jsonDataResult.setResult(903);
      jsonDataResult.setMessage("数据源不存在!");
      return jsonDataResult;
    }

    // 保存临时文件的名称
    List<String> uploadFileNames = new ArrayList<String>();

    // 保存临时文件地址
    String path = filepath + "/improtDatatemp";
    File uploadRootDir = new File(path);
    if (!uploadRootDir.exists()) {
      uploadRootDir.mkdirs();
    }

    // 将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
    CommonsMultipartResolver multipartResolver =
        new CommonsMultipartResolver(request.getSession().getServletContext());
    // 检查form中是否有enctype="multipart/form-data"
    if (multipartResolver.isMultipart(request)) {
      // 将request变成多部分request
      MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
      // 获取multiRequest 中所有的文件名
      Iterator<String> iter = multiRequest.getFileNames();

      while (iter.hasNext()) {
        // 一次遍历所有文件
        MultipartFile file = multiRequest.getFile(iter.next().toString());
        if (file != null) {
          Date currentTime = new Date();
          SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
          String filename =
              serviceID
                  + formatter.format(currentTime)
                  + Integer.toString((int) (Math.random() * 100 + 1))
                  + file.getOriginalFilename()
                      .substring(file.getOriginalFilename().lastIndexOf(".") - 1);
          String strExt =
              file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
          // 验证上传文件扩展名称是否是xls或xlsx
          if (!strExt.equals(".xls") && !strExt.equals(".xlsx")) {
            jsonDataResult.setResult(905);
            jsonDataResult.setMessage("文件格式错误!");
            return jsonDataResult;
          }
          uploadFileNames.add(filename);
          String filePath = path + "\\" + filename;
          File locafile = new File(filePath);
          // 上传
          file.transferTo(locafile);
        }
      }
    }

    // Excel数据转换Map<String,Object>对象List集合,并保存数据库
    Integer count = 0;
    if (uploadFileNames != null && uploadFileNames.size() > 0) {
      for (String strfilename : uploadFileNames) {
        // Excel转换list数据
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);

        List<Map<String, Object>> excellist =
            ExcelImportUtil.importExcel(new File(path + "\\" + strfilename), Map.class, params);

        // 删除临时文件

        try {
          // 导入到数据库
          ValidationInfoVo validationInfoVo =
              singleEditService.importData(cfgEdit, cfgDb, excellist, flag);
          count += validationInfoVo.getCount();
          jsonDataResult.setMessage(
              jsonDataResult.getMessage() + validationInfoVo.getValidateMessage());

        } catch (Exception e) {
          jsonDataResult.setResult(1);
          jsonDataResult.setData(0);
          jsonDataResult.setMessage(e.getMessage());
        }
      }
    }

    jsonDataResult.setResult(0);
    jsonDataResult.setData(count);

    return jsonDataResult;
  }

  /**
   * show 查询单表编辑主键字段 create by guoyanfei on 2018/10/08
   *
   * @param serviceID 服务ID
   * @return 主键字段
   */
  @RequestMapping(value = "/seletePrimaryKey", method = RequestMethod.GET)
  @ResponseBody
  @ApiOperation(value = "查询单表编辑主键字段")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public Object seletePrimaryKey(String serviceID) {

    JsonDataResult jsonResult = new JsonDataResult();
    try {
      if (serviceID == null || serviceID.equals("")) {
        jsonResult.setResult(901);
        jsonResult.setMessage("serviceID没有传入值或拼写错误!");
        return jsonResult;
      }
      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if (cfgEdit != null) {
        CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
        List<Map<String, String>> result = new ArrayList<>();
        String primaryKeys = singleEditService.getPrimaryKey(cfgEdit, cfgDb);
        if (primaryKeys != null && !primaryKeys.equals("")) {
          jsonResult.setResult(0);
          jsonResult.setMessage("查询成功!");
          jsonResult.setData(primaryKeys);
        } else {
          jsonResult.setResult(701);
          jsonResult.setMessage("查询失败!");
          jsonResult.setData(0);
        }
      } else {
        jsonResult.setResult(701);
        jsonResult.setMessage("服务不存在!");
        jsonResult.setData(0);
      }

    } catch (Exception e) {
      logger.error("查询单表编辑主键字段异常:", e);
      jsonResult.setResult(1);
      jsonResult.setMessage("查询单表编辑主键字段异常:" + e.getMessage());
    }
    return jsonResult;
  }

  /**
   * 通过主键查询数据 create by guoyanfei on 2019/07/20
   *
   * @param serviceID 服务ID
   * @param conQuery 查询条件
   * @return 结果
   */
  @RequestMapping(value = "/getDataByKey", method = RequestMethod.GET)
  @ResponseBody
  @ApiOperation(value = "通过主键查询数据")
  @ApiImplicitParams({
    @ApiImplicitParam(
        name = "serviceID",
        value = "服务编码",
        required = true,
        dataType = "String",
        paramType = "query"),
    @ApiImplicitParam(
        name = "conQuery",
        value = "查询条件",
        required = true,
        dataType = "String",
        paramType = "query")
  })
  public Object getDataBykey(String serviceID, String conQuery) {
    JsonDataResult jsonResult = new JsonDataResult();
    try {

      if (serviceID == null || serviceID.equals("")) {
        jsonResult.setResult(901);
        jsonResult.setMessage("serviceID没有传入值或拼写错误!");
        return jsonResult;
      }

      CfgEdit cfgEdit = redisCacheComponent.cfgEditRedisCache(serviceID);
      if (cfgEdit != null) {
        CfgDb cfgDb = redisCacheComponent.cfgDBRedisCache(cfgEdit.getDbKey());
        List<Map<String, Object>> result = new ArrayList<>();

        result = singleEditService.getDataPrimarykey(cfgEdit, cfgDb, conQuery);
        if (result != null && !result.equals("")) {
          jsonResult.setResult(0);
          jsonResult.setMessage("查询成功!");
          jsonResult.setData(result);
        } else {
          jsonResult.setResult(701);
          jsonResult.setMessage("查询失败!");
          jsonResult.setData(0);
        }
      } else {
        jsonResult.setResult(701);
        jsonResult.setMessage("服务不存在!");
        jsonResult.setData(0);
      }

    } catch (Exception e) {
      logger.error("查询通过主键查询数据异常:", e);
      jsonResult.setResult(1);
      jsonResult.setMessage("查询通过主键查询数据异常:" + e.getMessage());
    }

    return jsonResult;
  }
}
